﻿using AutoMapper;
using IMES.Common.Domain.DurianModel;
using IMES.Common.Dtos;
using IMES.Common.Infrastructure;
using MediatR;
using System.Net.WebSockets;

namespace Durian.API.Application.Commands.Process
{
    public class ProcessManagementSelectHandler : IRequestHandler<ProcessManagementSelectCommand, Result>
    {
        private readonly IMapper mapper;
        private readonly ILogger<ProcessManagementCreateHandler> logger;
        private readonly IBaseRepositorys<ProcessManagement> processManagementRepository;

        public ProcessManagementSelectHandler(IMapper mapper, ILogger<ProcessManagementCreateHandler> logger, IBaseRepositorys<ProcessManagement> processManagementRepository)
        {
            this.mapper = mapper;
            this.logger = logger;
            this.processManagementRepository = processManagementRepository;//工序管理仓储
        }

        /// <summary>
        /// 工序管理显示和查询
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(ProcessManagementSelectCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var res = new Result() { Code = (int)CodeEnum.search };
                var process = processManagementRepository.GetAll();

                //工序名称模糊查询、工序编码精确查询
                if (!string.IsNullOrEmpty(request.ProcessName))
                {
                    process = process.Where(a => a.ProcessName.Contains(request.ProcessName));
                }
                //工序编码精确查询
                if (request.ProcessNumber != 0)
                {
                    process = process.Where(a => a.ProcessNumber == request.ProcessNumber);
                }
                res.Code = (int)CodeEnum.search;
                res.Data = process;
                return res;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "工序管理显示和查询失败");
                return new Result() { Code = (int)CodeEnum.error, Messege = "工序管理显示和查询失败" };
            }
        }
    }
}
